const db = uniCloud.database()
const cmd = db.command

// 独立的工具函数
async function addLoginLog(userId, type, ctx) {
	const {
		CLIENTIP,
		USERAGENT
	} = ctx || {}
	try {
		await db.collection('login_logs').add({
			userId,
			type,
			ip: CLIENTIP,
			userAgent: USERAGENT,
			createTime: Date.now()
		})
	} catch (error) {
		console.error('记录登录日志失败:', error)
	}
}

module.exports = {
	// 手机号登录
	async loginByPhone(params) {
		try {
			const {
				phone,
				code
			} = params

			// 验证验证码
			const smsCode = await db.collection('sms_codes')
				.where({
					phone,
					code,
					expireTime: cmd.gt(Date.now())
				})
				.orderBy('createTime', 'desc')
				.limit(1)
				.get()

			if (smsCode.data.length === 0) {
				return {
					code: 400,
					msg: '验证码错误或已过期'
				}
			}

			// 查找或创建用户
			let user = await db.collection('users')
				.where({
					phone
				})
				.get()

			if (user.data.length === 0) {
				// 创建新用户
				const res = await db.collection('users').add({
					phone,
					nickname: `用户${phone.slice(-4)}`,
					avatar: '/static/default-avatar.png',
					createTime: Date.now(),
					updateTime: Date.now()
				})

				user = {
					_id: res.id,
					phone,
					nickname: `用户${phone.slice(-4)}`,
					avatar: '/static/default-avatar.png'
				}
			} else {
				user = user.data[0]
			}

			// 使用 uni-id 创建 token
			const tokenRes = await this.uniIdCommon.createToken({
				uid: user._id,
				needRefresh: true
			})

			if (tokenRes.errCode) {
				return {
					code: 500,
					msg: '创建token失败'
				}
			}

			// 添加登录日志
			await addLoginLog(user._id, 'phone', this.ctx)

			return {
				code: 200,
				data: {
					...user,
					token: tokenRes.token,
					tokenExpired: tokenRes.tokenExpired
				}
			}
		} catch (error) {
			console.error('手机登录错误:', error)
			return {
				code: 500,
				msg: '登录失败，请稍后重试'
			}
		}
	},

	// 微信登录
	async loginByWechat(params) {
		if (!params || !params.code) {
			return {
				code: 400,
				msg: '参数错误：缺少必要参数'
			}
		}

		try {
			const {
				code,
				userInfo
			} = params

			// 获取微信用户信息
			let wxRes;
			try {
				wxRes = await uniCloud.httpclient.request(
					'https://api.weixin.qq.com/sns/jscode2session', {
						method: 'GET',
						data: {
							appid: 'wxfa575231aabe0e47',
							secret: '8bd4fb3fd689e26f4b9e22a0792a74e0',
							js_code: code,
							grant_type: 'authorization_code'
						},
						dataType: 'json'
					}
				)
			} catch (wxError) {
				console.error('微信接口请求失败:', wxError);
				throw new Error('微信接口请求失败');
			}

			if (!wxRes || wxRes.status !== 200) {
				return {
					code: 400,
					msg: '微信登录失败: 接口响应异常'
				}
			}

			const responseData = wxRes.data;
			if (responseData.errcode) {
				return {
					code: 400,
					msg: `微信登录失败: ${responseData.errmsg || '未知错误'}`
				}
			}

			const {
				openid
			} = responseData;
			if (!openid) {
				return {
					code: 400,
					msg: '微信登录失败: 未获取到用户标识'
				}
			}

			// 查找或创建用户
			let user = await db.collection('users')
				.where({
					wxOpenId: openid
				})
				.get()

			if (user.data.length === 0) {
				// 创建新用户
				const res = await db.collection('users').add({
					wxOpenId: openid,
					nickname: userInfo?.nickName || `用户${openid.slice(-4)}`,
					avatar: userInfo?.avatarUrl || '/static/default-avatar.png',
					gender: userInfo?.gender || 0,
					createTime: Date.now(),
					updateTime: Date.now()
				})

				user = {
					_id: res.id,
					wxOpenId: openid,
					nickname: userInfo?.nickName || `用户${openid.slice(-4)}`,
					avatar: userInfo?.avatarUrl || '/static/default-avatar.png',
					gender: userInfo?.gender || 0
				}
			} else {
				// 已存在的用户，保留原有信息
				user = user.data[0]

				// 只在首次绑定微信时更新用户信息
				if (!user.wxOpenId) {
					await db.collection('users').doc(user._id).update({
						wxOpenId: openid,
						updateTime: Date.now()
					})
				}
			}

			// 使用 uni-id 创建 token
			const tokenRes = await this.uniIdCommon.createToken({
				uid: user._id,
				needRefresh: true
			})

			if (tokenRes.errCode) {
				return {
					code: 500,
					msg: '创建token失败'
				}
			}

			await addLoginLog(user._id, 'wechat', this.ctx)

			return {
				code: 200,
				data: {
					...user,
					token: tokenRes.token,
					tokenExpired: tokenRes.tokenExpired
				}
			}
		} catch (error) {
			console.error('微信登录错误:', error.message);
			return {
				code: 500,
				msg: '微信登录失败，请稍后重试'
			}
		}
	},

	// 自动登录
	async autoLogin(params) {
		const {
			token
		} = params

		try {
			// 使用 uni-id 验证 token
			const payload = await this.uniIdCommon.checkToken(token)
			if (payload.errCode) {
				return {
					code: 401,
					msg: '登录已过期'
				}
			}

			const user = await db.collection('users')
				.doc(payload.uid)
				.get()

			if (!user.data || user.data.length === 0) {
				return {
					code: 404,
					msg: '用户不存在'
				}
			}

			await addLoginLog(payload.uid, 'auto', this.ctx)

			return {
				code: 200,
				data: {
					...user.data[0],
					token: payload.token,
					tokenExpired: payload.tokenExpired
				}
			}
		} catch (error) {
			console.error('自动登录错误:', error.message);
			return {
				code: 500,
				msg: '自动登录失败'
			}
		}
	},

	// 获取用户信息
	async getUserInfo(params) {
		const { userId } = params
		try {
			const userRes = await db.collection('uni-id-users')
				.doc(userId)
				.get()

			if (!userRes.data || userRes.data.length === 0) {
				return {
					code: 404,
					msg: '用户不存在'
				}
			}

			const user = userRes.data[0]
			return {
				code: 200,
				data: user
			}
		} catch (error) {
			console.error('获取用户信息错误:', error)
			return {
				code: 500,
				msg: '获取用户信息失败'
			}
		}
	},

	async updateUserInfo(params) {
		const {
			userId,
			nickname,
			avatar
		} = params
		if (!userId || !nickname || !avatar) {
			return {
				code: 400,
				msg: '参数不完整'
			}
		}

		try {
			await db.collection('users')
				.doc(userId)
				.update({
					nickname,
					avatar,
					updateTime: Date.now()
				})

			return {
				code: 200,
				msg: '更新成功'
			}
		} catch (error) {
			console.error('更新用户信息失败:', error)
			return {
				code: 500,
				msg: '更新用户信息失败'
			}
		}
	},

	// 获取用户资料及关注/粉丝列表（带用户信息）
	async getUserProfileWithFollowInfo(params) {
		const { userId, type = 'follow', page = 1, pageSize = 20 } = params
		try {
			// 1. 获取用户基本信息
			const userRes = await db.collection('uni-id-users').doc(userId).get()
			if (!userRes.data || userRes.data.length === 0) {
				return { code: 404, msg: '用户不存在' }
			}
			const user = userRes.data[0]

			// 2. 获取关注/粉丝id列表和总数
			let ids = []
			let total = 0
			if (type === 'follow') {
				// 关注列表
				const followsRes = await db.collection('follows')
					.where({ followerId: userId })
					.skip((page - 1) * pageSize)
					.limit(pageSize)
					.get()
				ids = followsRes.data.map(item => item.followeeId)
				// 获取总数
				const countRes = await db.collection('follows').where({ followerId: userId }).count()
				total = countRes.total
			} else {
				// 粉丝列表
				const fansRes = await db.collection('follows')
					.where({ followeeId: userId })
					.skip((page - 1) * pageSize)
					.limit(pageSize)
					.get()
				ids = fansRes.data.map(item => item.followerId)
				// 获取总数
				const countRes = await db.collection('follows').where({ followeeId: userId }).count()
				total = countRes.total
			}

			// 3. 批量查用户信息
			let userList = []
			if (ids.length > 0) {
				const usersRes = await db.collection('uni-id-users')
					.where({ _id: db.command.in(ids) })
					.field({ _id: 1, nickname: 1, avatar: 1 })
					.get()
				userList = usersRes.data
			}

			// 4. 返回
			return {
				code: 200,
				data: {
					userId: user._id,
					nickname: user.nickname,
					avatar: user.avatar,
					list: userList, // 关注/粉丝用户信息列表
					total // 总关注数或粉丝数
				}
			}
		} catch (error) {
			console.error('获取用户资料及关注/粉丝列表错误:', error)
			return { code: 500, msg: '获取用户资料失败' }
		}
	},

	// 关注用户
	async followUser(params) {
		const { followerId, followeeId } = params
		if (!followerId || !followeeId) {
			return { code: 400, msg: '参数不完整' }
		}
		if (followerId === followeeId) {
			return { code: 400, msg: '不能关注自己' }
		}
		// 检查是否已关注
		const exist = await db.collection('follows').where({ followerId, followeeId }).count()
		if (exist.total > 0) {
			return { code: 409, msg: '已关注' }
		}
		await db.collection('follows').add({
			followerId,
			followeeId,
			createTime: Date.now()
		})
		return { code: 200, msg: '关注成功' }
	},

	// 取消关注用户
	async unfollowUser(params) {
		const { followerId, followeeId } = params
		if (!followerId || !followeeId) {
			return { code: 400, msg: '参数不完整' }
		}
		await db.collection('follows').where({ followerId, followeeId }).remove()
		return { code: 200, msg: '取消关注成功' }
	},

	// 手机号注册
	async registerByPhone(params) {
		try {
			const { phone } = params
			
			// 检查手机号格式
			if(!/^1\d{10}$/.test(phone)) {
				return {
					code: 400,
					msg: '手机号格式不正确'
				}
			}

			// 检查手机号是否已注册
			let user = await db.collection('users')
				.where({
					phone
				})
				.get()

			if(user.data.length > 0) {
				return {
					code: 400,
					msg: '该手机号已注册'
				}
			}

			// 创建新用户
			const res = await db.collection('users').add({
				phone,
				nickname: `用户${phone.slice(-4)}`,
				avatar: '/static/default-avatar.png',
				gender: 0,
				createTime: Date.now(),
				updateTime: Date.now()
			})

			user = {
				_id: res.id,
				phone,
				nickname: `用户${phone.slice(-4)}`,
				avatar: '/static/default-avatar.png',
				gender: 0
			}

			// 使用 uni-id 创建 token
			const tokenRes = await this.uniIdCommon.createToken({
				uid: res.id,
				needRefresh: true
			})

			if(tokenRes.errCode) {
				return {
					code: 500,
					msg: '创建token失败'
				}
			}

			// 添加注册日志
			await addLoginLog(res.id, 'phone', this.ctx)

			return {
				code: 200,
				data: {
					...user,
					token: tokenRes.token,
					tokenExpired: tokenRes.tokenExpired
				}
			}

		} catch(error) {
			console.error('手机号注册错误:', error)
			return {
				code: 500, 
				msg: '注册失败，请稍后重试'
			}
		}
	}
}